﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Net.Mail;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;
using MyUtility;
namespace ChoViet.Lib.Common
{
    public static class Utils
    {
        //public static readonly string RootPath = @"D:\Project\Example_Asp.net_MVC\Choviet.zoo.vn\SourceCode\ChoViet\ChoViet.CMS\";
        // Created by: VietLV
        public static string EncryptToMD5(string toEncrypt, string key)
        {
            byte[] keyArray; byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray; tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }

        public static string RandomString(int size)
        {
            StringBuilder sb = new StringBuilder();
            char c;
            Random rand = new Random();
            for (int i = 0; i < size; i++)
            {
                c = Convert.ToChar(Convert.ToInt32(rand.Next(65, 87)));
                sb.Append(c);
            }
            return sb.ToString();
        }
        public static int Random2Number(int minValue, int maxValue)
        {
            Random rand = new Random();
            return rand.Next(minValue,maxValue);
        }

        #region DecryptFromMD5. Created by: VietLV
        public static string DecryptFromMD5(string toDecrypt, string key)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(toDecrypt);
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;
            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            return UTF8Encoding.UTF8.GetString(resultArray);
        }
        #endregion

        #region DateTimeToString. Created by: VietLV
        public static string DateTimeToString(DateTime date)
        {
            if (date.Day == DateTime.Now.Day) return "Hôm nay " + date.Hour.ToString() + ":" + date.Minute.ToString();
            else if (date.Day == (DateTime.Now.Day - 1)) return "Hôm qua " + date.Hour.ToString() + ":" + date.Minute.ToString();
            else return "Ngày " + string.Format("{0:dd/MM/yyyy}", date);
        }
        #endregion

        public static bool IsNullOrEmpty(string s)
        {
            return (s == null || s.Trim().Length == 0);
        }

        /// <summary>
        /// Author: Takamaru Nguyen.
        /// Date: 03/08/2011.
        /// </summary>
        public static bool IsDocument(this string str, string doc)
        {
            if (string.IsNullOrEmpty(str))
                return false;
            if (string.IsNullOrEmpty(doc))
                return true;

            int lastIndex = str.LastIndexOf(".");
            return str.Substring(lastIndex, str.Length - lastIndex).Contains(doc);
        }
        public static int ParseInt(string s)
        {
            try
            {
                return Int32.Parse(s);
            }
            catch
            {
                return -1;
            }
        }
        public static int ParseInt(string s, int defaultvalue)
        {
            try
            {
                return Int32.Parse(s);
            }
            catch
            {
                return defaultvalue;
            }
        }
        public static int ParseInt(object s)
        {
            try
            {
                return Int32.Parse(s.ToString());
            }
            catch
            {
                return -1;
            }
        }
        public static void SendMail(string to, string from, string subject, string body)
        {
            /// Using default Smtp config (config in Web.config)
            SmtpClient client = new SmtpClient();
            client.EnableSsl = true;

            /// Mail details
            MailMessage msg = new MailMessage();

            try
            {
                msg.From = new MailAddress(from, "contact@ChoViet.vn");
                msg.To.Add(to);
                msg.SubjectEncoding = System.Text.Encoding.UTF8;
                msg.Subject = subject;
                msg.IsBodyHtml = true;
                msg.BodyEncoding = System.Text.Encoding.UTF8;
                msg.Body = body;
                msg.Priority = MailPriority.Normal;

                /// Enable one of the following method.
                client.Send(msg);
            }
            catch (Exception exp)
            {
                /// Throw exception to higher tier
                throw exp;
            }
        }
        public static DateTime ParseDateTime(string s, CultureInfo culture)
        {
            try
            {
                return DateTime.Parse(s, culture);
            }
            catch
            {
                return DateTime.Now;
            }
        }
        public static Decimal ParseDecimal(string s)
        {
            try
            {
                return Decimal.Parse(s);
            }
            catch
            {
                return 0;
            }
        }
        public static Decimal ParseDecimal(object s)
        {
            try
            {
                return Decimal.Parse(s.ToString());
            }
            catch
            {
                return 0;
            }
        }
        public static string EnCryptPassword(string strEncrypt)
        {
            byte[] hashedDataBytes;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(strEncrypt);
            UTF8Encoding encoder = new UTF8Encoding();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            hashedDataBytes = md5.ComputeHash(encoder.GetBytes(strEncrypt));
            md5.Clear();

            TripleDESCryptoServiceProvider tdesProvider = new TripleDESCryptoServiceProvider();
            tdesProvider.Key = hashedDataBytes;
            tdesProvider.Mode = CipherMode.ECB;
            tdesProvider.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdesProvider.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdesProvider.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        public static string DownloadDocument(int docId, string fileName)
        {
            string basePath = ConfigurationSettings.AppSettings["SiteBaseUrl"];// HttpContext.Current.Server.MapPath("/Uploads/");// ConfigurationSettings.AppSettings["SiteBasePath"];
            string path = basePath + "Files/";
            path += "doc_" + docId.ToString() + fileName.Substring(fileName.LastIndexOf('.'));
            return path;
        }
       
        /// <summary>
        /// Convert from string with structor to dictionary
        /// </summary>
        /// <param name="strInput">Format input: strKey1:value1[separator]strKey2:value2</param>
        /// <param name="separator">dash separator</param>
        /// <returns>Dictionary contain key and value</returns>
        public static Dictionary<object, object> StringToDictionary(string strInput, string separator)
        {
            var dict = new Dictionary<object, object>();
            string[] stringList = strInput.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (stringList != null && stringList.Length > 0)
                foreach (var str in stringList)
                {
                    var obj = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    dict.Add(obj[0].Trim(), obj[1].Trim());
                }
            return dict;
        }
        public static Dictionary<int, string> StringToDictionaryIntString(string strInput, string separator)
        {
            var dict = new Dictionary<int, string>();
            string[] stringList = strInput.Split(separator.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (stringList != null && stringList.Length > 0)
                foreach (var str in stringList)
                {
                    var obj = str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                    dict.Add(int.Parse(obj[0].Trim()), obj[1].Trim());
                }
            return dict;
        }
        public static IList<SelectListItem> GetSelectListItemInConfig(string strInput, string separator, int selectedValue)
        {
            var l = Utils.StringToDictionaryIntString(strInput, separator);
            IList<SelectListItem> list = new List<SelectListItem>();
            foreach (var item in l) {
                SelectListItem s = new SelectListItem();
                s.Text = item.Value;
                s.Value =""+ item.Key;
                s.Selected = item.Key == selectedValue ? true : false;
                list.Add(s);
            }
            return list;
        }
        public static List<int> GetListKeyInConfig(string strInput, string separator)
        {
            var l = Utils.StringToDictionaryIntString(strInput, separator);
            List<int> key=new List<int>();
            var txtValue=string.Empty;
            foreach (var item in l)
            {
                key.Add(item.Key);
            }
            return key;
        }
        public static string StringFormatPrecision(int intPrecision)
        {
            string precision = "{0:#,##0.";
            for (int i = 0; i < intPrecision; i++)
            {
                precision += "0";
            }
            precision += "}";
            return precision;
        }
        public static string DownloadFile(string fileName, string inFolderID, string inFolder, string rootUrl)
        {
            var path = rootUrl + "Uploads/" + inFolder + "/Files/" + inFolderID + "_" + fileName;
            return path;
        }
        public static string DownloadDocument(string fileName, string inFolderID, string inFolder, string rootUrl)
        {
            var path = rootUrl + "Documents/" + inFolder + "/"+inFolderID +"/"+ fileName;
            return path;
        }
        public static void DeleteFile(string fileName, string inFolderID, string inFolder, string rootPath)
        {
            string path = rootPath +"\\\\Documents\\\\"+inFolder+"\\\\"+inFolderID+ "\\\\" + fileName;
            if (File.Exists(path))
            {
                File.Delete(path);
            }
        }
        public static void DeleteInFolder(string inFolderID, string inFolder, string rootPath)
        {
            string path = rootPath + "\\\\Documents\\\\" + inFolder + "\\\\" + inFolderID;
            if (Directory.Exists(path))
                Directory.Delete(path, true);
        }
        public static Image CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
        {
            System.Drawing.Bitmap bmpOut = null;
            try
            {
                System.Drawing.Image loBMP = System.Drawing.Image.FromFile(lcFilename);
                ImageFormat loFormat = loBMP.RawFormat;
                decimal lnRatio;
                int lnNewWidth = 0;
                int lnNewHeight = 0;
                //*** If the image is smaller than a thumbnail just return it

                if (loBMP.Width < lnWidth && loBMP.Height < lnHeight)
                    return loBMP;
                if (loBMP.Width > loBMP.Height)
                {

                    lnRatio = (decimal)lnWidth / loBMP.Width;
                    lnNewWidth = lnWidth;
                    decimal lnTemp = loBMP.Height * lnRatio;
                    lnNewHeight = (int)lnTemp;
                }
                else
                {

                    lnRatio = (decimal)lnHeight / loBMP.Height;
                    lnNewHeight = lnHeight;
                    decimal lnTemp = loBMP.Width * lnRatio;
                    lnNewWidth = (int)lnTemp;
                }

                bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
                Graphics g = Graphics.FromImage(bmpOut);
                g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
                g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
                loBMP.Dispose();
            }
            catch(Exception exp)
            {
                MyLogfile.WriteLogData("Error", "CreateThumbnail: " + exp.ToString());
                return null;
            }
            return bmpOut;
        }
        public static void AddWaterMark(MemoryStream ms, string watermarkText, MemoryStream outputStream)
        {
            System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
            Graphics gr = Graphics.FromImage(img);
            Font font = new Font("Tahoma", (float)40);
            Color color = Color.FromArgb(50, 241, 235, 105);
            double tangent = (double)img.Height / (double)img.Width;
            double angle = Math.Atan(tangent) * (180 / Math.PI);
            double halfHypotenuse = Math.Sqrt((img.Height * img.Height) + (img.Width * img.Width)) / 2;
            double sin, cos, opp1, adj1, opp2, adj2;

            for (int i = 100; i > 0; i--)
            {
                font = new Font("Tahoma", i, FontStyle.Bold);
                SizeF sizef = gr.MeasureString(watermarkText, font, int.MaxValue);

                sin = Math.Sin(angle * (Math.PI / 180));
                cos = Math.Cos(angle * (Math.PI / 180));
                opp1 = sin * sizef.Width;
                adj1 = cos * sizef.Height;
                opp2 = sin * sizef.Height;
                adj2 = cos * sizef.Width;

                if (opp1 + adj1 < img.Height && opp2 + adj2 < img.Width)
                    break;
                //
            }

            StringFormat stringFormat = new StringFormat();
            stringFormat.Alignment = StringAlignment.Center;
            stringFormat.LineAlignment = StringAlignment.Center;

            gr.SmoothingMode = SmoothingMode.AntiAlias;
            gr.RotateTransform((float)angle);
            gr.DrawString(watermarkText, font, new SolidBrush(color), new Point((int)halfHypotenuse, 0), stringFormat);

            img.Save(outputStream, ImageFormat.Jpeg);
        }

        //public static System.Drawing.Image CreateThumbnail(string pathImg, int lnWidth, int lnHeight)
        //{

        //    System.Drawing.Image bmpOut = null;
        //    string path = pathImg;
        //    try
        //    {
        //        //Bitmap loBMP = new Bitmap(path);
        //        System.Drawing.Image loBMP = System.Drawing.Image.FromFile(path);
        //        ImageFormat loFormat = loBMP.RawFormat;

        //        decimal src_ratio = (decimal)loBMP.Width / loBMP.Height;
        //        decimal thumb_ratio = (decimal)lnWidth / lnHeight;
        //        // Get min size (height or width)
        //        int new_width = 0;
        //        int new_height = 0;
        //        if (thumb_ratio > src_ratio)
        //        {
        //            new_width = lnWidth;
        //            new_height = (int)(lnWidth / src_ratio);
        //        }
        //        else
        //        {
        //            new_width = (int)(lnHeight * src_ratio);
        //            new_height = lnHeight;
        //        }
        //        bmpOut = new Bitmap(new_width, new_height, PixelFormat.Format24bppRgb);
        //        Graphics g = Graphics.FromImage(bmpOut);
        //        g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
        //        g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
        //        g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
        //        g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
        //        g.FillRectangle(Brushes.White, 0, 0, new_width, new_height);
        //        g.DrawImage(loBMP, 0, 0, new_width, new_height);
        //        bmpOut = ImageCrop(bmpOut, lnWidth, lnHeight, AnchorPosition.Center);
        //        loBMP.Dispose();
        //        return bmpOut;
        //    }
        //    catch
        //    {
        //        return null;
        //    }
        //}

        public static System.Drawing.Image ImageCrop(System.Drawing.Image imgPhoto, int Width, int Height, AnchorPosition Anchor)
        {

            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;
            int destX = 0;
            int destY = 0;

            float nPercent = 0;
            float nPercentW = 0;
            float nPercentH = 0;

            nPercentW = ((float)Width / (float)sourceWidth);
            nPercentH = ((float)Height / (float)sourceHeight);

            if (nPercentH < nPercentW)
            {
                nPercent = nPercentW;
                switch (Anchor)
                {
                    case AnchorPosition.Top:
                        destY = 0;
                        break;
                    case AnchorPosition.Bottom:
                        destY = (int)(Height - (sourceHeight * nPercent));
                        break;
                    default:
                        destY = (int)((Height - (sourceHeight * nPercent)) / 2);
                        break;
                }
            }
            else
            {
                nPercent = nPercentH;
                switch (Anchor)
                {
                    case AnchorPosition.Left:
                        destX = 0;
                        break;
                    case AnchorPosition.Right:
                        destX = (int)(Width - (sourceWidth * nPercent));
                        break;
                    default:
                        destX = (int)((Width - (sourceWidth * nPercent)) / 2);
                        break;
                }

            }

            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(Width, Height);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver;
            grPhoto.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.GammaCorrected;
            grPhoto.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
            grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            grPhoto.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);
            grPhoto.Dispose();
            return bmPhoto;
        }
        
        public static string GetThumbFullPath(int artId, string imgPath, int width, int height, string baseUrl)
        {
            string path = string.Empty;
            if (imgPath != null && imgPath != string.Empty)
            {
                path = baseUrl + string.Format("thumb/art_{0}_{1}_", width, height) + artId.ToString() + imgPath.Substring(imgPath.LastIndexOf('.'));
            }
            return path;
        }
        public static string GetThumbFullPath(int artId, string imgPath, int width, int height, string baseUrl, string pathFile)
        {
            string path = string.Empty;
            if (File.Exists(pathFile))
            {
                if (imgPath != null && imgPath != string.Empty)
                {
                    path = baseUrl + string.Format("thumb/art_{0}_{1}_", width, height) + artId.ToString() + imgPath.Substring(imgPath.LastIndexOf('.'));
                }
                return path;
            }
            else
            {
                var http="http://";
                var link= baseUrl.Replace(http,string.Empty);
                return http + link.Substring(0, link.IndexOf("/")) + Globals.DefaultLogo;
            }
           
        }
        public static string GetSiteThumbFullPath(int artId, string imgPath, int width, int height, string basePath)
        {
            string path = string.Empty;
           //string basePath = ConfigurationSettings.AppSettings["SiteBasePath"];// HttpContext.Current.Server.MapPath("/Uploads/");// ConfigurationSettings.AppSettings["SiteBasePath"];
            if (imgPath != null && imgPath != string.Empty)
            {
                path = basePath + string.Format("thumb\\art_{0}_{1}_", width, height) + artId.ToString() + imgPath.Substring(imgPath.LastIndexOf('.'));
            }
            return path;
        }
        public static string GetSitePathImgNotReSize(int artId, string imgPath, string basePath)
        {
            string path = string.Empty;
            //string basePath = ConfigurationSettings.AppSettings["SiteBasePath"];// HttpContext.Current.Server.MapPath("/Uploads/");// ConfigurationSettings.AppSettings["SiteBasePath"];
            if (imgPath != null && imgPath != string.Empty)
            {
                path = basePath + artId.ToString() + "_" + imgPath;
            }
            return path;
        }
        public static string GenThumbnail(int artId, int width, int height, string fileName,string basePath,string rootPath,string baseUrl)
        {
            string fileNameGen = GetSiteThumbFullPath(artId, fileName, width, height, basePath);
            string fileNotGen = GetSitePathImgNotReSize(artId, fileName, basePath);
            if (File.Exists(fileNameGen))
            {
                if (File.GetLastWriteTime(fileNotGen) > File.GetLastWriteTime(fileNameGen))
                {
                    System.Drawing.Image bmThumb = CreateThumbnail(fileNotGen, width, height);
                    SaveThumbnail(bmThumb, width, height, fileNameGen,rootPath);
                }
            }
            else
            {
                System.Drawing.Image bmThumb = CreateThumbnail(fileNotGen, width, height);
                SaveThumbnail(bmThumb, width, height, fileNameGen,rootPath);
            }
            return GetThumbFullPath(artId, fileName, width, height, baseUrl, fileNameGen);

        }
        
        public static string SaveThumbnail(System.Drawing.Image bmThumb, int width, int height, string filePath, string rootPath)
        {
            var path = rootPath + filePath;
            try
            {
                if (bmThumb != null)
                {
                    //var path = System.AppDomain.CurrentDomain.BaseDirectory + filePath;
                     
                    //if (!Directory.Exists(path.Substring(0, filePath.LastIndexOf("\\"))))
                    //{
                    //    // If it doesn't then we just create it before going any further
                    //    Directory.CreateDirectory(filePath.Substring(0, filePath.LastIndexOf("\\")));
                    //}
                    bmThumb.Save(path, bmThumb.RawFormat);
                    bmThumb.Dispose();
                    return "/" + filePath.Replace('\\', '/');
                }
                else return null;
            }
            catch(Exception exp)
            {
                MyLogfile.WriteLogData("Error", "SaveThumbnail: " + exp.ToString());
                return null; 
            }
        }
        public static string[] GetImageInFolder(int inFolder, string rootPath, string rootUrl)
        {
            try
            {
                string path = rootPath + "\\\\" + inFolder.ToString() + "\\\\";
                string[] files = Directory.Exists(path) ? Directory.GetFiles(path) : new string[0];
                if (files.Length == 0) return new string[0];

                string thumbOfFile = string.Empty;
                string notResizeOfFile = string.Empty;
                if (files.Length > 0)
                {
                    string[] listfile = new string[files.Length];
                    int index = 0;
                    foreach (string file in files)
                    {
                        FileInfo fileinfo = new FileInfo(file);
                        listfile[index] = GetImageFullPathInFolder(inFolder.ToString(), fileinfo.Name, rootUrl);
                        index++;
                    }
                    return listfile;
                }
                else return new string[0];
            }
            catch (Exception exp)
            {
                return new string[0];
            }

        }
        public static string GetImageFullPathInFolder(string InFolder, string fileName, string rooUrl)
        {
            string path = string.Empty;
            if (fileName != null && fileName != string.Empty)
            {
                path = rooUrl.LastIndexOf("/") == rooUrl.Length - 1 ? rooUrl + string.Format("{0}/{1}", InFolder, fileName) :
                    rooUrl + string.Format("/{0}/{1}", InFolder, fileName);
            }
            return path;
        }
        public static string[] GenThumbnailInFolder(int inFolder, int width, int height, string SiteRootPath, string SiteRootUrl)
        {
            var path = string.Format("{0}{1}", SiteRootPath, inFolder.ToString());
            var thumbpath = string.Format("{0}{1}{2}", SiteRootPath, "Thumb\\", inFolder.ToString());

            if (!Directory.Exists(thumbpath))
            {
                // If it doesn't then we just create it before going any further
                Directory.CreateDirectory(thumbpath);
            }
            string[] files =Directory.Exists(path)? Directory.GetFiles(path): new string[0];
            if (files.Length <= 0) return new string[0];
            string thumbOfFile = string.Empty;
            string notResizeOfFile = string.Empty;
            if (files.Length > 0)
            {
                string[] listfile = new string[files.Length];
                int index = 0;
                foreach (string file in files)
                {
                    FileInfo fileinfo = new FileInfo(file);
                    thumbOfFile = thumbpath + "\\\\" + string.Format("{0}_{1}_{2}",width,height, fileinfo.Name);
                    notResizeOfFile = path + "\\\\" + fileinfo.Name;
                    if (File.Exists(thumbOfFile))
                    {
                        if (File.GetLastWriteTime(notResizeOfFile) > File.GetLastWriteTime(thumbOfFile))
                        {
                            System.Drawing.Image bmThumb = CreateThumbnail(notResizeOfFile, width, height);
                            SaveThumbnail(bmThumb, width, height, thumbOfFile,SiteRootPath);
                        }
                    }
                    else
                    {
                        System.Drawing.Image bmThumb = CreateThumbnail(notResizeOfFile, width, height);
                        SaveThumbnail(bmThumb, width, height, thumbOfFile,SiteRootPath);

                    }
                    listfile[index] = GetThumbFullPathInFolder(inFolder.ToString(), fileinfo.Name,width,height, SiteRootUrl);
                    index++;
                }
                return listfile;

            }
            else return new string[0];

        }
        public static string GetThumbFullPathInFolder(string InFolder, string fileName,int width, int height, string SiteRootUrl)
        {
            string path = string.Empty;
            if (fileName != null && fileName != string.Empty)
            {
                path = SiteRootUrl + "Thumb/" + InFolder + "/" + width + "_" + height + "_" + fileName;
            }
            return path;
        }
        public static string ReadNumber(double number)
        {
            var b = new StringBuilder();
            if (number <= 0) return "0";
            if (number < Math.Pow(10, 6))
            {
                b.Append(number);
                b.Append(" nghìn");
                return b.ToString();
            }
            if (Math.Pow(10, 6) <= number && number < Math.Pow(10, 9))
            {
                b.Append(Math.Round(number / Math.Pow(10, 6), 2));
                b.Append(" triệu");
                return b.ToString();
            }
            if (number >= Math.Pow(10, 9))
            {
                b.Append(Math.Round(number / Math.Pow(10, 9), 2));
                b.Append(" tỷ");
                return b.ToString();
            }
            return null;
        }
        public static string GetIcon(string fileName, string SiteRootUrl)
        {
            var path = SiteRootUrl != string.Empty ? SiteRootUrl + "icon-16-" : "/images/ftc/icon-16-";
            var extent = fileName.Substring(fileName.LastIndexOf(".") + 1).ToLower();
            switch (extent) { 
                case "pdf":
                    path = path + "pdf.png";
                    break;
                case "xlsx":
                case "xls":
                    path = path + "excel.png";
                    break;
                case "doc":
                case "docx":
                    path = path + "word.png";
                    break;
                case "rar":
                case "zip":
                    path = path + "zip.png";
                    break;
                default:
                    path = path + "zip.png";
                    break;
            }
            return path;
        }
        public static List<SelectListItem> ListGioiTinh()
        {
            var data = new List<SelectListItem>();
            var list = new SelectListItem()
            {
                Text = "Nam",
                Value = "Nam"

            };
            var list1 = new SelectListItem()
            {
                Text = "Nữ",
                Value = "Nữ"

            };
            data.Add(list);
            data.Add(list1);
            return data;

        }
        //lay huong         
        public static List<SelectListItem> ListHuongNha()
        {
            string[] dsHuongNha = { "Tây Bắc", "Bắc", "Đông Bắc", "Tây", "Đông", "Tây Nam", "Nam", "Đông Nam" };
            var data = new List<SelectListItem>();

            foreach (var item in dsHuongNha)
            {
                var list = new SelectListItem()
                {
                    Value = item.Trim().ToString(),
                    Text = item.Trim().ToString()
                };
                data.Add(list);
            }
            return data;

        }
        public static List<SelectListItem> ListNam()
        {
            var data = new List<SelectListItem>();



            int namhientai = DateTime.Now.Year;
            var listnam = new List<int>();
            for (int i = namhientai; i < namhientai + 40; i++)
            {
                var list = new SelectListItem()
                {
                    Value = i.ToString(),
                    Text = i.ToString()

                };
                data.Add(list);
            }

            return data;
        }
        private static string[] DoWLabels = new string[]
        {
              "C.Nhật", "T.Hai", "T.Ba", "T.Tư", "T.Năm", "T.Sáu", "T.Bảy" 
        };
        public static string ToDayOfWeekLabel(this DateTime dt) { return DoWLabels[(int)dt.DayOfWeek]; }

        //Reduce Image size VietLV: 25-06-2012
        public static string ReduceImageSize(string path,string rootPath, int quality, HttpPostedFileBase fbfile)
        {    
            if (fbfile != null && fbfile.ContentLength > 0)
            {
                if (quality < 0 || quality > 100) quality = 50;
                //var fullpath = System.AppDomain.CurrentDomain.BaseDirectory + path; 
                var fullpath = rootPath + path;
                Stream str = fbfile.InputStream;
                System.Drawing.Image img = System.Drawing.Image.FromStream(str);


                // Encoder parameter for image quality 
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                // Jpeg image codec 
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                img.Save(fullpath, jpegCodec, encoderParams);
                return path.Replace('\\', '/');
            }
            else return null;
        }
        //Overload Reduce Image size VietLV: 19-08-2012
        public static string ReduceImageSize(string path,string rootPath,string id, int quality, HttpPostedFileBase fbfile)
        {
            if (fbfile != null && fbfile.ContentLength > 0)
            {
                if (quality < 0 || quality > 100) quality = 50;
                //var fullpath = System.AppDomain.CurrentDomain.BaseDirectory + path; 
                var tempPath = rootPath + path + id + "\\"; // fixx cứng thư mục trên server. server để động gặp lỗi
                if (!Directory.Exists(tempPath))
                    Directory.CreateDirectory(tempPath);

                Stream str = fbfile.InputStream;
                System.Drawing.Image img = System.Drawing.Image.FromStream(str);

                var fullpath = tempPath + id +"_" + fbfile.FileName;
                // Encoder parameter for image quality 
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                // Jpeg image codec 
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");

                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                img.Save(fullpath, jpegCodec, encoderParams);
                return path.Replace('\\', '/')+id+"/"+id+"_"+fbfile.FileName;
            }
            else return null;
        }

        /// <summary> 
        /// Returns the image codec with the given mime type 
        /// </summary> 
        private static ImageCodecInfo GetEncoderInfo(string mimeType)
        {
            // Get image codecs for all image formats 
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();

            // Find the correct image codec 
            for (int i = 0; i < codecs.Length; i++)
                if (codecs[i].MimeType == mimeType)
                    return codecs[i];
            return null;
        }

        #region DateTimeToString. Created by: VietLV
        public static string DateTimeToStringFormat(DateTime date)
        {
            DateTime present = DateTime.Now;
            if (date.Year == present.Year && date.Month == present.Month && date.Day == present.Day) return "Hôm nay " + date.Hour.ToString() + ":" + date.Minute.ToString();
            else if (date.Year == present.Year && date.Month == present.Month && date.Day == (present.Day - 1)) return "Hôm qua " + date.Hour.ToString() + ":" + date.Minute.ToString();
            else
            {
                string st = date.ToDayOfWeekLabel() + " " + string.Format("{0:dd/MM/yyyy HH:mm}", date);
                return date.ToDayOfWeekLabel()+" " + string.Format("{0:dd/MM/yy HH:mm}", date);
            }
        }
        #endregion
        #region Check New Ad Today. Created by: VietLV
        public static string CheckNewAdToDay(DateTime date)
        {
            DateTime present = DateTime.Now;
            if (date.Year == present.Year && date.Month == present.Month && date.Day == present.Day)
            {
                return "<img src=\"/Images/new_Moi.gif\"/>";
            }
            else
                return string.Empty;
        }
        #endregion

        public static string GetTemplateEmail(string path, string fileName)
        {
            string rootPath = AppDomain.CurrentDomain.BaseDirectory;
            string fullpath = rootPath + path + fileName;

            StreamReader Srd = new StreamReader(fullpath);
            var c = "";
            string content = "";
            while ((c = Srd.ReadLine()) != null)
            {
                content += c;
            }
            Srd.Dispose();
            Srd.Close();
            return content;
        }
    }
}
